package com.financing.controller.agent;
import java.util.Date;
import java.util.Map;

import com.financing.model.Data;
import com.financing.model.agent.Visit;
import com.financing.model.user.User;
import com.financing.service.agent.VisitService;
import com.financing.util.Json;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

/**
 *  拜访记录控制器
 * @since 2017-06-06
 * @author 无处不在的二叔
 */
public class VisitController extends Controller {
	private VisitService visit = new VisitService();


	/**
	 * 拜访信息编辑
	 */
	public void edit() { 
		User creater = getAttr("user");
		
		int id = getParaToInt("id",0);
		Visit v = id>0 ? Visit.me.findById(id) : new Visit();
		User u = User.me.findById(getParaToInt("userId"));
		if(u.getId()>0){

			// 设置用户信息
			v.setUserId(u.getId());
			v.setRealName(u.getRealName());
			v.setMobile(getPara("mobile"));
			
			// 设置客服信息 
			User agent = User.me.findById(u.getAgentId());
			v.setAgentId(agent.getId());
			v.setAgentRealName(agent.getRealName());
			v.setIsValid(getPara("isValid"));
			v.setIsSolve(getParaToInt("isSolve",0));
			v.setMatter(getPara("matter"));
			v.setSolve(getPara("solve"));
			v.setTel(getPara("tel"));
			v.setType(getPara("type"));
			v.setCreaterId(creater.getId());
			v.setCreaterRealName(creater.getRealName());
			
			if(id>0 ? v.update() : v.setCreateTime(new Date()).save()){
				renderJson(Json.ok("拜访信息编辑成功！")); 
			}else{
				renderJson(Json.error("拜访信息编辑失败！"));
			}
		}else{
			renderJson(Json.error("客户信息不存在！"));
		}
	}	
	 
	/**
	 * 拜访列表
	 */
	public void list() { 
		User u = getAttr("user");
		Map<String,String> params = Data.flat(getParaMap());
		params.put("agentId", visit.getAgents(u.getId()));
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);
		Page<Visit> p = visit.list(page,size,params);
		renderJson(Json.ok("数据获取成功！", Data.put("page",p)));
	}	
	 
	/**
	 * 拜访列表
	 */
	public void solve() { 
		Visit v = Visit.me.findById(getParaToInt("id",0));
		if(v!=null) {
			v.setSolve(getPara("solve"));
			v.setSolve2(getPara("solve2"));
			v.setSolve3(getPara("solve3"));
			v.setIsSolve(getParaToInt("isSolve",0));
			v.update();
			renderJson(Json.ok("操作成功！"));
		} else {
			renderJson(Json.error("访问记录不存在！"));
		}
	}

	/**
	 * 查看信息
	 */
	public void info() { 
		Visit v = Visit.me.findById(getParaToInt("id",0));
		renderJson(Json.ok("数据获取成功！", Data.put("item",v)));
	}	
}
 